import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-06-10
 * Time: 18:09
 */
public class jdbcInsert {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        // 1.创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_mysql5?characterEncoding=utf-8&&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        // 2.与数据库建立关联
        Connection connection = dataSource.getConnection();//数据源获取链接
        // 3.构造sql语句 并解析
        System.out.print("请输入书名: ");
        String name = scanner.nextLine();
        System.out.print("请输入作者: ");
        String author = scanner.nextLine();
        System.out.print("请输入价格: ");
        int price = scanner.nextInt();
        scanner.nextLine();
        System.out.print("请输入类型: ");
        String type = scanner.nextLine();

        String sql1 = "insert into booklist values (?,?,?,?)";

       // String sql1 = "insert into booklist values ('STL源码刨析','侯捷',123,'编程')";
        PreparedStatement statement = connection.prepareStatement(sql1);//解析
        statement.setString(1,name);
        statement.setString(2,author);
        statement.setInt(3,price);
        statement.setString(4,type);

        System.out.println(statement);
        // 4.执行sql语句
        int ret = statement.executeUpdate();
        System.out.println("ret = " + ret);
        // 5.关闭资源
        statement.close();
        connection.close();
    }
}
